package com.eascs.workflow.common.type;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 类型父类， 模拟枚举类型规避序列化的问题
 */
public abstract class BaseType implements Serializable {
	private static final long serialVersionUID = -4558770845744270233L;

	private String code; // code
	private String description; // 描述

	protected BaseType() {
	}

	protected BaseType(String code, String description) {
		this.code = code;
		this.description = description;
	}

	@SuppressWarnings("unchecked")
	public static <T extends BaseType> List<T> getAll(Class<T> clazz) {
		List<T> list = new ArrayList<T>();
		try {
			Field[] fieldlist = clazz.getDeclaredFields();
			for (Field field : fieldlist) {
				if (field.getType().isAssignableFrom(clazz)) {
					list.add((T) field.get(null));
				}
			}
		} catch (Exception e) {
		}
		return list;
	}

	public static <T extends BaseType> T valueOf(Class<T> clazz, String index) {
		try {
			List<T> list = (List<T>) BaseType.getAll(clazz);
			for (T t : list) {
				if (t.getCode().equals(index)) {
					return t;
				}
			}
		} catch (Exception e) {
		}
		return null;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((description == null) ? 0 : description.hashCode());
		result = prime * result + ((code == null) ? 0 : code.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;

		BaseType other = (BaseType) obj;
		if (description == null) {
			if (other.description != null)
				return false;
		} else if (!description.equals(other.description)) {
			return false;
		}
		if (code == null) {
			if (other.code != null)
				return false;
		} else if (!code.equals(other.code)) {
			return false;
		}
		return true;
	}

	public String getDescription() {
		return description;
	}

	@Override
	public String toString() {
		return "BaseType [code=" + code + ", description=" + description + "]";
	}

}